<template>
	<view class="uni-list list-pd ">
		<view class="uni-list-cell cell-pd">
			<view class="uni-uploader">
				<view class="uni-uploader-head block-bottom-line psr">
					<view class="uni-uploader-title pdt10 pdb10 upImg fs16 text-black"> {{title}}</view>
					<view class="uni-uploader-info" style="line-height: 100upx;">{{imageList.length}}张</view>
				</view>
				<view class="uni-uploader-body pdb10">
					<view class="uni-uploader__files pdl15">
						<block v-for="(image,index) in imageList" :key="index">
							<view class="uni-uploader__file">
								<image class="uni-uploader__img" :src="image.path" :data-src="image.path" @tap="previewImage"></image>
								<view v-if="isClear" class="clearImg" @tap="clearImg(index)">
									<icon type='clear' size='20' />
								</view>
								<block v-if="image.finish==false&&image.percent<100">
									<view class="progress-box"  >
										<progress :percent="image.percent" activeColor="#1376FB"  stroke-width="3" backgroundColor="#999" />
									</view>
									<view class="mask-loading">上传中...</view>
								</block>
							</view>
						</block>
						<view v-if="isUpload" class="uni-uploader__input-box">
							<view class="uni-uploader__input" @tap="chooseImage"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import isObject from 'lodash/isObject'
	import isEmpty from 'lodash/isEmpty'
	import cloneDeep from 'lodash/cloneDeep'

	export default{
		props:{
			title:{
				type:String,
				default:'图片上传'
			},
			//是否需要上传图片
			isUpload:{
				type:Boolean,
				default:true,
			},
			uploadUrl:{
				type:String,
				default:''
			},
			isClear:{
				type:Boolean,
				default:true,
			},
			maxCount:{
				type:Number,
				default:0
			},
			initialValue:{
				type:Array,
				default(){
					return []
				}
			},
		},
		data(){
			return {
				imageList:this.initialValue?this.initialValue:[],
			};
		},
		watch:{
			initialValue(value){
				this.imageList = value;
			},
			imageList(value){
				this.imageList = value;
			}
		},
		computed:{
			previewList(){
				let newPayload = [];
				this.imageList.forEach((item,key)=>{
					newPayload.push(item.path);
				});
				return newPayload;
			}
		},
		methods:{
			chooseImage: async function() {
				let $this = this;

				if(!$this.uploadUrl){
					uni.showToast({
						title:"上传url不存在！",
						duration: 2000,
					})
					return false;
				}

				if(this.maxCount>0&&this.imageList.length === this.maxCount){
					let isContinue = await this.isFullImg();
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					success: async (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						let header = {
							'Content-Type': 'multipart/form-data'
						};
						let cookie = "";
						if(this.globalCode && this.globalCode.globalCode && this.globalCode.globalCode.HTTPS_SESSION_KEY){
							uni.getStorageSync(this.globalCode.globalCode.HTTPS_SESSION_KEY)
						}
						let	path = tempFilePaths[0];//预览回显图片
						if (!isEmpty(cookie)) {
							header = { ...header,
								Cookie: cookie
							};
						}
						let tempO = {
							percent:0,
							finish:false,
							path
						};
						$this.imageList = $this.imageList.concat([{...tempO}]);
						let uploadFile = uni.uploadFile({
							url: $this.uploadUrl,
							filePath: path,
							header: header,
							name: 'Filedata',
							success: (uploadFileRes) => {
								if(uploadFileRes&&200==uploadFileRes.statusCode){
									try{
										let data = JSON.parse(uploadFileRes.data);
										if(data&&isObject(data)){
											let paths = data.path.split('/');
											let newPayload = cloneDeep($this.imageList);
											newPayload.forEach((item)=>{
												if(item.path == path){
													item['fileName'] = paths[paths.length - 1];
													item['saveName'] = (item['fileName'].split('.'))[0];
													item['savePath'] = data.savePath;
													item['finish'] = true;
													// console.log('data:',data);
													// item = {...item,...data,
													// 	fileName:paths[paths.length - 1],
													// 	saveName:(item['fileName'].split('.'))[0],
													// 	finish:true};
													// console.log('item:',item);

												}
											});
											// console.log('newPayload:',newPayload);
											$this.imageList = newPayload;
											// console.log('$this.imageList:',$this.imageList);
										}
									}catch(e){
										//TODO handle the exception
										console.error('uploadTask return data not is josn')
									}
								}
							}
						});

						uploadFile.onProgressUpdate(res=>{
							$this.imageList.forEach((item)=>{
								if(item.path == path){
									item['percent'] = res.progress;
								}
							})
						});
					}
				})
			},
			isFullImg: function() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src;
				uni.previewImage({
					current: current,
					urls: this.previewList
				})
			},
			clearImg(index){
				if(this.imageList[index]){
					this.imageList.splice(index,1);
				}
			},
			getFieldValue(){
				let arr = [...this.imageList],payload = [];
				arr.forEach((item,key)=>{
					delete item['finish'];
					delete item['percent'];
					payload.push(item);
				});
				return payload;
			},
		}
	}
</script>

<style lang="scss">
	@import "./index.scss";
	@import "../common/common.scss";
	.uni-uploader__file{
		position: relative;
		.mask-loading{
			z-index: 1;
			background-color: rgba(0,0,0,.8);
			color: #fff;
			text-align: center;
			position: absolute;
			top: 0;
			left: 0;
			bottom: 3upx;
			right: 0;
			font-size: 24upx;
			padding-top: 40%;

		}
		.clearImg{
			position: absolute;
			top:-10upx;
			right:-10upx;
			z-index: 2;
		}
	}
	.uni-uploader__input-box{
		border-color: #DEEAF2;
		border-radius: 5upx;
	}
</style>
